package com.langll.ai.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.langll.ai.base.service.impl.BaseServiceImpl;
import com.langll.ai.stock.mapper.TicketMapper;
import com.langll.ai.stock.model.Ticket;
import com.langll.ai.stock.service.ITicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 股票查询票据信息 服务实现类
 * </p>
 *
 * @author langll
 * @since 2025-04-21
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TicketServiceImpl extends BaseServiceImpl<TicketMapper, Ticket> implements ITicketService {

    private final TicketMapper ticketMapper;

    public TicketServiceImpl(TicketMapper ticketMapper) {
        super(ticketMapper);
        this.ticketMapper = ticketMapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Ticket createTicket(String symbol, String period, String startDate, String endDate, String adjust, Float timeout) {
        Ticket ticket = new Ticket();
        ticket.setSymbol(symbol);
        ticket.setPeriod(period);
        ticket.setStartDate(startDate);
        ticket.setEndDate(endDate);
        ticket.setAdjust(adjust);
        ticket.setTimeout(timeout);
        ticket.setStatus(0); // 初始状态为未执行
        
        ticketMapper.insert(ticket);
        return ticket;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTicketStatus(Long id, Integer status, Long resultId) {
        Ticket ticket = ticketMapper.selectById(id);
        if (ticket == null) {
            log.error("票据不存在，ID: {}", id);
            return false;
        }
        
        ticket.setStatus(status);
        if (resultId != null) {
            ticket.setResultId(resultId);
        }
        
        return ticketMapper.updateById(ticket) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Ticket updateTicket(Ticket ticket) {
        // 检查票据是否存在
        Ticket existingTicket = ticketMapper.selectById(ticket.getId());
        if (existingTicket == null) {
            log.error("票据不存在，ID: {}", ticket.getId());
            return null;
        }
        
        // 更新票据信息（只更新有值的字段）
        if (ticket.getSymbol() != null) {
            existingTicket.setSymbol(ticket.getSymbol());
        }
        if (ticket.getPeriod() != null) {
            existingTicket.setPeriod(ticket.getPeriod());
        }
        if (ticket.getStartDate() != null) {
            existingTicket.setStartDate(ticket.getStartDate());
        }
        if (ticket.getEndDate() != null) {
            existingTicket.setEndDate(ticket.getEndDate());
        }
        if (ticket.getAdjust() != null) {
            existingTicket.setAdjust(ticket.getAdjust());
        }
        if (ticket.getTimeout() != null) {
            existingTicket.setTimeout(ticket.getTimeout());
        }
        if (ticket.getStatus() != null) {
            existingTicket.setStatus(ticket.getStatus());
        }
        if (ticket.getResultId() != null) {
            existingTicket.setResultId(ticket.getResultId());
        }
        
        // 更新数据库
        ticketMapper.updateById(existingTicket);
        
        return existingTicket;
    }

    @Override
    public List<Ticket> getTicketsBySymbol(String symbol) {
        LambdaQueryWrapper<Ticket> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Ticket::getSymbol, symbol)
                   .orderByDesc(Ticket::getCreateTime);
        
        return ticketMapper.selectList(queryWrapper);
    }

    @Override
    public List<Ticket> getPendingTickets() {
        LambdaQueryWrapper<Ticket> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Ticket::getStatus, 0)
                   .orderByAsc(Ticket::getCreateTime);
        
        return ticketMapper.selectList(queryWrapper);
    }

    @Override
    public List<Ticket> getRunningTickets() {
        LambdaQueryWrapper<Ticket> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Ticket::getStatus, 1)
                   .orderByAsc(Ticket::getCreateTime);
        
        return ticketMapper.selectList(queryWrapper);
    }

    @Override
    public List<Ticket> getAllTickets() {
        LambdaQueryWrapper<Ticket> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Ticket::getCreateTime);
        
        return ticketMapper.selectList(queryWrapper);
    }

    @Override
    public List<Ticket> getCompletedTickets() {
        LambdaQueryWrapper<Ticket> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Ticket::getStatus, 2)
                   .orderByDesc(Ticket::getCreateTime);
        
        return ticketMapper.selectList(queryWrapper);
    }
}